import { createRouter, createWebHistory } from 'vue-router'
import { useMenuStore } from "@/stores/menu.js"


const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { title: '账户设置' }
      },
      {
        path: "/:pathMatch(.*)",
        meta: { title: "404" },
        name: "404",
        component: () => import("@/views/404.vue"),
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from) => {
  const menuStore = useMenuStore()

  if (to.meta.title) {
    document.title = `${to.meta.title}-MonoAdmin`
  }

  // 如果访问登录页
  if (to.path === '/login') {
    return true
  } else {
    if (menuStore.menuList.length === 0) {
      const accessRoutes = await menuStore.getMenus()

      for (let index = 0; index < accessRoutes.length; index++) {
        const item = accessRoutes[index];

        if (!router.hasRoute(item.name)) {
          router.addRoute('Layout', item)
        }

      }

      return to.fullPath

    }

    return true
  }


})

export default router